<template>
  <el-scrollbar ref="wrapperRef">
    <div ref="spinRef" :style="spinStyle" v-loading="loading" :element-loading-text="loadingTip"
      :element-loading-svg="loadingSvg" class="custom-loading-svg" element-loading-svg-view-box="-10, -10, 950, 950">
      <slot></slot>
    </div>
  </el-scrollbar>
</template>

<script lang="ts" setup>
import { computed, CSSProperties, nextTick, ref, unref, watchEffect } from 'vue';
import { ComponentRef, ElRef } from '/#/index';
import loadingSvg from '@/components/Table/src/loadingSvg'

const emit = defineEmits<{
  (e: 'height-change', realHeight: number): void
}>()

interface Props {
  minHeight?: number
  fullScreen?: boolean
  loading: boolean
  height?: number
  modelValue: boolean
  loadingTip: string
  useWrapper: boolean
  footerOffset?: number,
  modalFooterHeight?: number,
  modalHeaderHeight?: number
}
const props = withDefaults(defineProps<Props>(), {
  fullScreen: false,
  modelValue: false,
  loading: true,
  loadingTip: '数据正在拼命加载中...',
  useWrapper: true,
  footerOffset: 0,
  modalFooterHeight: 74,
  modalHeaderHeight: 57,
  minHeight: 200
})

const wrapperRef = ref<ComponentRef>(null)
const spinRef = ref<ElRef>(null)
const realHeightRef = ref(0);
const minRealHeightRef = ref(0);

let realHeight = 0;


watchEffect(() => {
  props.useWrapper && setModalHeight()
})



async function setModalHeight() {
  // 解决在弹窗关闭的时候监听还存在,导致再次打开弹窗没有高度
  // 加上这个,就必须在使用的时候传递父级的modelValue
  if (!props.modelValue) return;
  const wrapperRefDom = unref(wrapperRef);
  if (!wrapperRefDom) return;

  const bodyDom = wrapperRefDom.$el.parentElement;
  if (!bodyDom) return;
  bodyDom.style.padding = '0';
  await nextTick();

  try {
    const modalDom = bodyDom.parentElement && bodyDom.parentElement.parentElement;
    if (!modalDom) return;

    const modalRect = getComputedStyle(modalDom as Element).top;
    const modalTop = Number.parseInt(modalRect);

    let maxHeight =
      window.innerHeight -
      modalTop * 2 +
      (props.footerOffset! || 0) -
      props.modalFooterHeight -
      props.modalHeaderHeight;

    // 距离顶部过进会出现滚动条
    if (modalTop < 40) {
      maxHeight -= 26;
    }
    await nextTick();
    const spinEl = unref(spinRef);

    if (!spinEl) return;
    await nextTick();
    // if (!realHeight) {
    realHeight = spinEl.scrollHeight;
    // }

    if (props.fullScreen) {
      realHeightRef.value =
        window.innerHeight - props.modalFooterHeight - props.modalHeaderHeight - 28;
    } else {
      realHeightRef.value = props.height
        ? props.height
        : realHeight > maxHeight
          ? maxHeight
          : realHeight;
    }
    emit('height-change', unref(realHeightRef));

  } catch (error) {
    console.log(error);
  }
}
console.log('readhedit',realHeightRef.value)
const spinStyle = computed((): CSSProperties => {
  return {
    minHeight: `${props.minHeight}px`,
    // [props.fullScreen ? 'height' : 'maxHeight']: `${unref(realHeightRef)}px`,
  };
});
</script>